package com.java.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLOutput;

/**
 * @ClassNameLoginFilter
 * @Description 自定义zuul过滤器
 * @Author liufei
 * @Date2021/9/3 11:42
 * @Version V1.0
 **/
@Component
public class LoginFilter extends ZuulFilter {
    /**
     * 定义过滤器类型
     * pre
     * routing
     * post
     * error
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 指定过滤器的执行顺序
     * 返回值越小，执行顺序越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * 过滤器是否生效
     * true:使用此过滤器
     * false:不使用此过滤器
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 执行过滤器的业务逻辑
     * 身份认证
     * access-token
     * 获取request请求
     * 通过request获取access-token
     * 判断token是否为空
     * 在zuul网关中通过requestContext的上下文对象，可以获取对象request对象
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //获取zuul提供的上下文对象RequestContext
        RequestContext requestContext = RequestContext.getCurrentContext();
        //从RequestContext中获取request
        HttpServletRequest request = requestContext.getRequest();
        //获取请求参数
        String token = request.getParameter("access-token");
        //判断
        if(null == token || "".equals(token)){
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        System.out.println("执行了过滤器");
        return null;
    }
}
